package com.newear.datacenter;

import android.content.Context;
import android.util.SparseArray;

import com.alibaba.fastjson.JSONObject;
import com.newear.bean.HistoryRecordInfo;
import com.newear.bean.ReportInfo;
import com.newear.bean.WeatherInfo;
import com.newear.util.MyLogger;
import com.newear.util.MySharedPreferences;
import com.newear.util.Validator;

/**
 * Created by josan_tang on 2016/07/19.
 * 数据提供类
 * 调用RemoteServer对应方法，解析json数据得到请求需要的对象
 */
public class DataProvider {
    private static final String TAG = "DataProvider";
    private static volatile DataProvider instance;
    private static final String UNKOWN_ERROR_CODE = "255";
    private static final String UNKOWN_ERROR_MESSAGE = "未知错误";
    private static final String NOT_NETWORK_CODE = "254";
    private static final String NOT_NETWORK_MESSAGE = "网络异常，请检查网络";

    /**
     * 用户json数据传递参数的key
     */
    /**
     * 状态码
     */
    private static final String ERRNO = "error";
    /**
     * 消息提示
     */
    private static final String MESSAGE = "msg";
    /**
     * 数据
     */
    private static final String DATA = "body";

    private DataProvider() {

    }

    /**
     * 得带DataProvider对象
     *
     * @return 这里为多线程单例
     */
    public static DataProvider getInstance() {
        if (instance == null) {
            synchronized (DataProvider.class) {
                if (instance == null) {
                    instance = new DataProvider();
                }
            }
        }
        return instance;
    }
    /**
     * 用户登录
     *
     * @return 请求端需要的对象
     * String[]
     * result[0]-errno 255-未知错误 254-网络异常
     * result[1]-msg.
     * result[2]-userInfo.
     */
    public SparseArray<Object> userLogin(Context appContext, String userName, String userPwd) {
        SparseArray<Object> result = new SparseArray<Object>();

        String resultJson = RemoteServer.userLogin(appContext, userName, userPwd);  //json数据
        if (!Validator.isEffective(resultJson)) {   //返回json数据为空
            result.put(0, NOT_NETWORK_CODE);
            result.put(1, NOT_NETWORK_MESSAGE);
            return result;
        }
        try {
            JSONObject infos = JSONObject.parseObject(resultJson);
            if (infos != null) {
                if (infos.has(ERRNO)) {
                    result.put(0, infos.optString(ERRNO));
                }
                if (infos.has(MESSAGE)) {
                    result.put(1, infos.optString(MESSAGE));
                }
                if (infos.has("jwt")) {
                    String token = infos.optString("jwt");
                    if (Validator.isEffective(token)) {
                        MySharedPreferences.getInstance().setToken(appContext, token);
                        // 保存下来，方便token过期的刷新
                        MySharedPreferences.getInstance().setUsername(appContext, userName);
                        MySharedPreferences.getInstance().setPassword(appContext, userPwd);
                    }
                }
                return result;
            }
        } catch (Exception e) {
            result.put(0, UNKOWN_ERROR_CODE);
            result.put(1, UNKOWN_ERROR_MESSAGE);
            return result;
        }
        return null;
    }

    public SparseArray<Object> getWeather(Context appContext, double lat, double lon) {
        SparseArray<Object> result = new SparseArray<Object>();

        String resultJson = RemoteServer.getWeather(appContext, lat, lon);  //json数据
        if (!Validator.isEffective(resultJson)) {   //返回json数据为空
            result.put(0, NOT_NETWORK_CODE);
            result.put(1, NOT_NETWORK_MESSAGE);
            return result;
        }
        try {
            JSONObject infos = JSONObject.parseObject(resultJson);
            if (infos != null) {
                if (infos.has("status_code") && infos.has("error")) {
                    int statusCode = infos.optInt("status_code");
                    String error = infos.optString("error");
                    if (statusCode == 401 && "Invalid token".equals(error)) {
                        // token过期重新登录
                        String username = MySharedPreferences.getInstance().getUsername(appContext);
                        String pwd = MySharedPreferences.getInstance().getPassword(appContext);
                        if (Validator.isEffective(username) && Validator.isEffective(pwd)) {
                            SparseArray<Object> loginResult = userLogin(appContext, username, pwd);
                            if (loginResult != null) {
                                String errorCode = (String) loginResult.get(0);
                                if ("0".equals(errorCode)) {
                                    resultJson = RemoteServer.getWeather(appContext, lat, lon);  //json数据
                                    MyLogger.e("" + resultJson);
                                    if (!Validator.isEffective(resultJson)) {   //返回json数据为空
                                        result.put(0, NOT_NETWORK_CODE);
                                        result.put(1, NOT_NETWORK_MESSAGE);
                                        return result;
                                    }
                                    infos = JSONObject.parseObject(resultJson);
                                    if (infos != null) {
                                        result.put(0, "0");
                                        WeatherInfo weatherInfo = new WeatherInfo();
                                        if (weatherInfo.parse(infos)) {
                                            result.put(1, weatherInfo);
                                        }
                                    }
                                }
                            }
                        }
                    }
                } else {
                    result.put(0, "0");
                    WeatherInfo weatherInfo = new WeatherInfo();
                    if (weatherInfo.parse(infos)) {
                        result.put(1, weatherInfo);
                    }
                }
                return result;
            }
        } catch (Exception e) {
            result.put(0, UNKOWN_ERROR_CODE);
            result.put(1, UNKOWN_ERROR_MESSAGE);
            return result;
        }
        return null;
    }

    // 得到报告
    public SparseArray<Object> getReport(Context appContext) {
        SparseArray<Object> result = new SparseArray<Object>();
        String resultJson = RemoteServer.getReport(appContext);  //json数据
        MyLogger.e("" + resultJson);
        if (!Validator.isEffective(resultJson)) {   //返回json数据为空
            result.put(0, NOT_NETWORK_CODE);
            result.put(1, NOT_NETWORK_MESSAGE);
            return result;
        }
        try {
            JSONObject infos = JSONObject.parseObject(resultJson);
            if (infos != null) {
                if (infos.has("status_code") && infos.has("error")) {
                    int statusCode = infos.optInt("status_code");
                    String error = infos.optString("error");
                    if (statusCode == 401 && "Invalid token".equals(error)) {
                        // token过期重新登录
                        String username = MySharedPreferences.getInstance().getUsername(appContext);
                        String pwd = MySharedPreferences.getInstance().getPassword(appContext);
                        if (Validator.isEffective(username) && Validator.isEffective(pwd)) {
                            SparseArray<Object> loginResult = userLogin(appContext, username, pwd);
                            if (loginResult != null) {
                                String errorCode = (String) loginResult.get(0);
                                if ("0".equals(errorCode)) {
                                    resultJson = RemoteServer.getReport(appContext);  //json数据
                                    MyLogger.e("" + resultJson);
                                    if (!Validator.isEffective(resultJson)) {   //返回json数据为空
                                        result.put(0, NOT_NETWORK_CODE);
                                        result.put(1, NOT_NETWORK_MESSAGE);
                                        return result;
                                    }
                                    infos = JSONObject.parseObject(resultJson);
                                    if (infos != null) {
                                        result.put(0, "0");
                                        ReportInfo reportInfo = new ReportInfo();
                                        if (reportInfo.parse(infos)) {
                                            result.put(1, reportInfo);
                                        }
                                    }
                                }
                            }
                        }
                    }
                } else {
                    result.put(0, "0");
                    ReportInfo reportInfo = new ReportInfo();
                    if (reportInfo.parse(infos)) {
                        result.put(1, reportInfo);
                    }
                }
                return result;
            }
        } catch (Exception e) {
            result.put(0, UNKOWN_ERROR_CODE);
            result.put(1, UNKOWN_ERROR_MESSAGE);
            return result;
        }
        return null;
    }

    // 得到报告
    public SparseArray<Object> getReportById(Context appContext, int id) {
        SparseArray<Object> result = new SparseArray<Object>();
        String resultJson = RemoteServer.getReportById(appContext, id);  //json数据
        if (!Validator.isEffective(resultJson)) {   //返回json数据为空
            result.put(0, NOT_NETWORK_CODE);
            result.put(1, NOT_NETWORK_MESSAGE);
            return result;
        }
        try {
            JSONObject infos = JSONObject.parseObject(resultJson);
            if (infos != null) {
                if (infos.has("status_code") && infos.has("error")) {
                    int statusCode = infos.optInt("status_code");
                    String error = infos.optString("error");
                    if (statusCode == 401 && "Invalid token".equals(error)) {
                        // token过期重新登录
                        String username = MySharedPreferences.getInstance().getUsername(appContext);
                        String pwd = MySharedPreferences.getInstance().getPassword(appContext);
                        if (Validator.isEffective(username) && Validator.isEffective(pwd)) {
                            SparseArray<Object> loginResult = userLogin(appContext, username, pwd);
                            if (loginResult != null) {
                                String errorCode = (String) loginResult.get(0);
                                if ("0".equals(errorCode)) {
                                    resultJson = RemoteServer.getReportById(appContext, id);  //json数据
                                    MyLogger.e("" + resultJson);
                                    if (!Validator.isEffective(resultJson)) {   //返回json数据为空
                                        result.put(0, NOT_NETWORK_CODE);
                                        result.put(1, NOT_NETWORK_MESSAGE);
                                        return result;
                                    }
                                    infos = JSONObject.parseObject(resultJson);
                                    if (infos != null) {
                                        result.put(0, "0");
                                        ReportInfo reportInfo = new ReportInfo();
                                        if (reportInfo.parse(infos)) {
                                            result.put(1, reportInfo);
                                        }
                                    }
                                }
                            }
                        }
                    }
                } else {
                    result.put(0, "0");
                    ReportInfo reportInfo = new ReportInfo();
                    if (reportInfo.parse(infos)) {
                        result.put(1, reportInfo);
                    }
                }
                return result;
            }
        } catch (Exception e) {
            result.put(0, UNKOWN_ERROR_CODE);
            result.put(1, UNKOWN_ERROR_MESSAGE);
            return result;
        }
        return null;
    }

    // 得到历史报告
    public SparseArray<Object> getHistoryReport(Context appContext, String date, int page) {
        SparseArray<Object> result = new SparseArray<Object>();
        String resultJson = RemoteServer.getHistoryReport(appContext, date, page);  //json数据
        if (!Validator.isEffective(resultJson)) {   //返回json数据为空
            result.put(0, NOT_NETWORK_CODE);
            result.put(1, NOT_NETWORK_MESSAGE);
            return result;
        }
        try {
            JSONObject infos = JSONObject.parseObject(resultJson);
            if (infos != null) {
                if (infos.has("status_code") && infos.has("error")) {
                    int statusCode = infos.optInt("status_code");
                    String error = infos.optString("error");
                    if (statusCode == 401 && "Invalid token".equals(error)) {
                        // token过期重新登录
                        String username = MySharedPreferences.getInstance().getUsername(appContext);
                        String pwd = MySharedPreferences.getInstance().getPassword(appContext);
                        if (Validator.isEffective(username) && Validator.isEffective(pwd)) {
                            SparseArray<Object> loginResult = userLogin(appContext, username, pwd);
                            if (loginResult != null) {
                                String errorCode = (String) loginResult.get(0);
                                if ("0".equals(errorCode)) {
                                    resultJson = RemoteServer.getHistoryReport(appContext, date, page);  //json数据
                                    MyLogger.e("" + resultJson);
                                    if (!Validator.isEffective(resultJson)) {   //返回json数据为空
                                        result.put(0, NOT_NETWORK_CODE);
                                        result.put(1, NOT_NETWORK_MESSAGE);
                                        return result;
                                    }
                                    infos = JSONObject.parseObject(resultJson);
                                    if (infos != null) {
                                        result.put(0, "0");
                                        HistoryRecordInfo historyRecordInfo = new HistoryRecordInfo();
                                        if (historyRecordInfo.parse(infos)) {
                                            result.put(1, historyRecordInfo);
                                        }
                                    }
                                }
                            }
                        }
                    }
                } else {
                    result.put(0, "0");
                    HistoryRecordInfo historyRecordInfo = new HistoryRecordInfo();
                    if (historyRecordInfo.parse(infos)) {
                        result.put(1, historyRecordInfo);
                    }
                }
                return result;
            }
        } catch (Exception e) {
            result.put(0, UNKOWN_ERROR_CODE);
            result.put(1, UNKOWN_ERROR_MESSAGE);
            return result;
        }
        return null;
    }

    /**
     * 上传脸部表情
     *
     * @return
     */
    public SparseArray<Object> uploadFacePhoto(Context appContext) {
        SparseArray<Object> result = new SparseArray<Object>();
        String resultJson = RemoteServer.uploadFacePhoto(appContext);
        if (!Validator.isEffective(resultJson)) {   //
            result.put(0, NOT_NETWORK_CODE);
            result.put(1, NOT_NETWORK_MESSAGE);
            return result;
        }
        try {
            JSONObject infos = JSONObject.parseObject(resultJson);
            if (infos != null) {
                if (infos.has("status_code") && infos.has("error")) {
                    int statusCode = infos.optInt("status_code");
                    String error = infos.optString("error");
                    if (statusCode == 401 && "Invalid token".equals(error)) {
                        // token过期重新登录
                        String username = MySharedPreferences.getInstance().getUsername(appContext);
                        String pwd = MySharedPreferences.getInstance().getPassword(appContext);
                        if (Validator.isEffective(username) && Validator.isEffective(pwd)) {
                            SparseArray<Object> loginResult = userLogin(appContext, username, pwd);
                            if (loginResult != null) {
                                String errorCode = (String) loginResult.get(0);
                                if ("0".equals(errorCode)) {
                                    resultJson = RemoteServer.uploadFacePhoto(appContext);  //json数据
                                    MyLogger.e("" + resultJson);
                                    if (!Validator.isEffective(resultJson)) {   //返回json数据为空
                                        result.put(0, NOT_NETWORK_CODE);
                                        result.put(1, NOT_NETWORK_MESSAGE);
                                        return result;
                                    }
                                    infos = JSONObject.parseObject(resultJson);
                                    if (infos != null) {
                                        if (infos.has("faceDetectRes")) {
                                            result.put(0, infos.optString("faceDetectRes"));
                                        }
                                        if (infos.has("id")) {
                                            result.put(1, infos.optString("id"));
                                        }
                                    }
                                }
                            }
                        }
                    }
                } else {
                    if (infos.has("faceDetectRes")) {
                        result.put(0, infos.optString("faceDetectRes"));
                    }
                    if (infos.has("id")) {
                        result.put(1, infos.optString("id"));
                    }
                }
                return result;
            }
        } catch (Exception e) {
            result.put(0, UNKOWN_ERROR_CODE);
            result.put(1, UNKOWN_ERROR_MESSAGE);
            return result;
        }
        return result;
    }


    /**
     * 上传舌部表情
     *
     * @return
     */
    public SparseArray<Object> uploadTonguePhoto(Context appContext) {
        SparseArray<Object> result = new SparseArray<Object>();
        String resultJson = RemoteServer.uploadTonguePhoto(appContext);
        if (!Validator.isEffective(resultJson)) {   //
            result.put(0, NOT_NETWORK_CODE);
            result.put(1, NOT_NETWORK_MESSAGE);
            return result;
        }
        try {
            JSONObject infos = JSONObject.parseObject(resultJson);
            if (infos != null) {
                if (infos.has("status_code") && infos.has("error")) {
                    int statusCode = infos.optInt("status_code");
                    String error = infos.optString("error");
                    if (statusCode == 401 && "Invalid token".equals(error)) {
                        // token过期重新登录
                        String username = MySharedPreferences.getInstance().getUsername(appContext);
                        String pwd = MySharedPreferences.getInstance().getPassword(appContext);
                        if (Validator.isEffective(username) && Validator.isEffective(pwd)) {
                            SparseArray<Object> loginResult = userLogin(appContext, username, pwd);
                            if (loginResult != null) {
                                String errorCode = (String) loginResult.get(0);
                                if ("0".equals(errorCode)) {
                                    resultJson = RemoteServer.uploadTonguePhoto(appContext);  //json数据
                                    MyLogger.e("" + resultJson);
                                    if (!Validator.isEffective(resultJson)) {   //返回json数据为空
                                        result.put(0, NOT_NETWORK_CODE);
                                        result.put(1, NOT_NETWORK_MESSAGE);
                                        return result;
                                    }
                                    infos = JSONObject.parseObject(resultJson);
                                    if (infos != null) {
                                        if (infos.has("tongueDetectRes")) {
                                            result.put(0, infos.optString("tongueDetectRes"));
                                        }
                                        if (infos.has("id")) {
                                            result.put(1, infos.optString("id"));
                                        }
                                    }
                                }
                            }
                        }
                    }
                } else {
                    if (infos.has("tongueDetectRes")) {
                        result.put(0, infos.optString("tongueDetectRes"));
                    }
                    if (infos.has("id")) {
                        result.put(1, infos.optString("id"));
                    }
                }
                return result;
            }
        } catch (Exception e) {
            result.put(0, UNKOWN_ERROR_CODE);
            result.put(1, UNKOWN_ERROR_MESSAGE);
            return result;
        }
        return result;
    }

    // 得到报告
    public SparseArray<Object> checkVip(Context appContext, String id) {
        SparseArray<Object> result = new SparseArray<Object>();
        String resultJson = RemoteServer.checkVip(appContext, id);  //json数据
        if (!Validator.isEffective(resultJson)) {   //返回json数据为空
            result.put(0, NOT_NETWORK_CODE);
            result.put(1, NOT_NETWORK_MESSAGE);
            return result;
        }
        try {
            JSONObject infos = JSONObject.parseObject(resultJson);
            if (infos != null) {
                if (infos.has("status_code") && infos.has("error")) {
                    int statusCode = infos.optInt("status_code");
                    String error = infos.optString("error");
                    if (statusCode == 401 && "Invalid token".equals(error)) {
                        // token过期重新登录
                        String username = MySharedPreferences.getInstance().getUsername(appContext);
                        String pwd = MySharedPreferences.getInstance().getPassword(appContext);
                        if (Validator.isEffective(username) && Validator.isEffective(pwd)) {
                            SparseArray<Object> loginResult = userLogin(appContext, username, pwd);
                            if (loginResult != null) {
                                String errorCode = (String) loginResult.get(0);
                                if ("0".equals(errorCode)) {
                                    resultJson = RemoteServer.checkVip(appContext, id);  //json数据
                                    MyLogger.e("" + resultJson);
                                    if (!Validator.isEffective(resultJson)) {   //返回json数据为空
                                        result.put(0, NOT_NETWORK_CODE);
                                        result.put(1, NOT_NETWORK_MESSAGE);
                                        return result;
                                    }
                                    infos = JSONObject.parseObject(resultJson);
                                    if (infos != null) {
                                        result.put(0, "0");
                                        if (infos.has("status")) {
                                            result.put(1, infos.optBoolean("status"));
                                        }
                                    }
                                }
                            }
                        }
                    }
                } else {
                    result.put(0, "0");
                    if (infos.has("status")) {
                        result.put(1, infos.optBoolean("status"));
                    }
                }
                return result;
            }
        } catch (Exception e) {
            result.put(0, UNKOWN_ERROR_CODE);
            result.put(1, UNKOWN_ERROR_MESSAGE);
            return result;
        }
        return null;
    }
}
